package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import java.util.Arrays;

import static com.shanxia.codec.Decoder.*;

/**
 * S -> C
 * 平台回复“即插即充”启动充电结果
 */
@Data
public class Cmd209 extends ProtocolDataBase {

    public static final int MIN_SIZE = 56;

    private int v1;
    private int v2;
    private String sn;                  // 充电桩编码
    private int pileNum;                // 充电枪号
    private String vin;                 // 车辆VIN码

    public Cmd209(){
        super.setCmd(209);
    }

    public static Cmd209 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd209 cmd = new Cmd209();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        //数据域长度
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 32字节充电桩编码
        cmd.sn = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 32), true);
        offset += 32;
        // 1字节充电枪号
        cmd.pileNum = getUint8(dataField[offset++]);
        // 17字节车辆 VIN 码
        cmd.vin = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 17), true);
        return cmd;
    }

    @Override
    public byte[] getDataField() {
        byte[] data = new byte[MIN_SIZE];
        int offset = 0;
        getBytesAsUint16(data, offset, this.v1);
        offset += 2;
        getBytesAsUint16(data, offset, this.v2);
        offset += 2;
        // 32字节充电桩编码
        encodeAscii(data, this.sn, 32, offset);
        offset += 32;
        // 1字节充电枪号
        data[offset++] = (byte) pileNum;
        // 17字节车辆 VIN 码
        encodeAscii(data, this.vin, 17, offset);
        return data;
    }
}
